<template>
  <div class="app-container">
    <!--工具栏-->
    <div
      v-if="crud.props.searchToggle"
      class="crud-group"
    >
      <!-- 搜索 -->
      <el-input
        v-model="query.scriptPackName"
        clearable
        size="small"
        placeholder="任务名称"
        style="width:200px"
        class="filter-item"
      />
      <el-select
        v-model="query.clusterId"
        clearable
        size="small"
        placeholder="请选择集群"
        class="filter-item"
      >
        <el-option
          v-for="item in clusterLists"
          :key="item.key"
          :label="item.value"
          :value="item.key"
        />
      </el-select>
      <el-select
        v-model="query.packState"
        clearable
        size="small"
        placeholder="请选择打包状态"
        class="filter-item"
      >
        <el-option
          v-for="item in packStatusList"
          :key="item.key"
          :label="item.value"
          :value="item.key"
        />
      </el-select>
      <rrOperation :crud="crud" />
    </div>
    <crudOperation :permission="permission" />
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      @select="crud.selectChange"
      @select-all="crud.selectAllChange"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        v-if="columns.visible('scriptPackName')"
        :show-overflow-tooltip="true"
        min-width="150"
        label="任务名称"
        prop="scriptPackName"
      />
      <el-table-column
        v-if="columns.visible('clusterName')"
        label="集群名称"
        prop="clusterName"
      />
      <el-table-column
        v-if="columns.visible('packState')"
        label="状态"
        prop="packState"
      >
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.packState==='FINISH'"
            size="small"
            type="success"
          >完成</el-tag>
          <el-tag
            v-if="scope.row.packState==='SCANNING'"
            size="small"
          >扫描中</el-tag>
          <el-tag
            v-if="scope.row.packState==='SCANFINISH'"
            size="small"
            type="success"
          >扫描完成</el-tag>
          <el-tag
            v-if="scope.row.packState==='FAIL'"
            size="small"
            type="danger"
          >失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns.visible('packState')"
        label="进度"
        prop="packState"
        width="310px"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.scanTotal !== null">
            <el-tag
              style="margin: 0 5px"
              type="info"
            >总数: {{ scope.row.scanTotal }}</el-tag>
            <el-tag
              style="margin: 0 5px"
              type="success"
            >成功: {{ scope.row.scanSuccessNumber }}</el-tag>
            <el-tag
              style="margin: 0 5px"
              type="warning"
            >告警: {{ scope.row.scanWarnNumber }}</el-tag>
            <el-tag
              style="margin: 0 5px"
              type="danger"
            >异常: {{ scope.row.scanErrorNumber }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns.visible('fileObtainingType')"
        label="文件获取方式"
        prop="fileObtainingType"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.fileObtainingType==='git'">git拉取</span>
          <span v-if="scope.row.fileObtainingType==='upload'">手动上传</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns.visible('demandCode')"
        label="发布编码"
        prop="demandCode"
      />
      <el-table-column
        v-if="columns.visible('onlineDate')"
        label="发布日期"
        prop="onlineDate"
      />
      <el-table-column
        v-if="columns.visible('createBy')"
        label="操作人"
        prop="createBy"
      />
      <el-table-column
        v-if="columns.visible('createTime')"
        sortable
        label="操作时间"
        prop="createTime"
        width="140px"
      />
      <el-table-column label="查看详情">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="crud.toEdit(scope.row)"
          >查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <!--分页组件-->
      <pagination />
    </div>
    <!--表单渲染-->
    <el-dialog
      :close-on-click-modal="false"
      :before-close="()=>{
        crud.cancelCU(),
        $refs.checkResultRef.resetQueryData()
      }"
      :visible.sync="crud.status.cu > 0"
      :title="active === 0 ? '创建打包任务' : ( active === 1 ? '查看扫描清单' : '新建发布包' )"
      width="1100px"
      top="5vh"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        :inline="true"
        label-width="120px"
      >
        <el-row>
          <el-col :span="24">
            <el-steps
              :active="active"
              finish-status="success"
              simple
            >
              <el-step title="上传发布脚本" />
              <el-step title="确认扫描结果" />
<!--              <el-step title="创建发布包" />-->
            </el-steps>
          </el-col>
        </el-row>

        <div
          v-if="active === 0"
          style="margin-top: 20px"
        >
          <upload-script
            v-model="form"
            :disable-form="crud.form.id !== null"
            :check-list-tmp="checkListTmp"
            :init-script-list-tmp="initScriptListTmp"
            :biz-script-list-tmp="bizScriptListTmp"
            :cycle-script-list-tmp="cycleScriptListTmp"
          />
          <div
            class="dialog-footer"
            style="width:100%;text-align: center;margin-top: 20px"
          >
            <!-- @click="()=>{
                crud.cancelCU()
                crud.resetForm()
              }"
             -->
            <el-button
              @click="closeClick"
            >关 闭</el-button>
            <el-button
              :loading="this.nextStepLoading === true"
              type="primary"
              @click="submitCU"
            >下一步(扫描)</el-button>
          </div>
        </div>
        <div
          v-if="active === 1"
          style="margin-top: 20px"
        >
          <check-result
            v-if="crud.status.cu > 0"
            ref="checkResultRef"
            :pack-task-id="form.id"
            @next="packScriptFile"
            @pre="active --"
          />

        </div>
        <div
          v-if="active === 2"
          style="margin-top: 20px"
        >
          <submit-publish v-model="form" />
          <div
            class="dialog-footer"
            style="width:100%;text-align: center;margin-top: 20px; display:inline-block"
          >
            <el-button @click="active --">上一步</el-button>
            <el-button
              type="primary"
              :loading="isPackSubmitting"
              @click="submitPublishTask"
            >提 交</el-button>
          </div>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import CRUD, { crud, form, header, presenter } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/extend/script/pack/CRUD.operation'
import uploadScript from './components/uploadScript/index'
import checkResult from './components/scanList/index'
// import submitPublish from './components/submitPublish/index'
import pagination from '@crud/Pagination'
import scriptPackTaskApi from '@/api/script/pack/scriptPackTask'
// import scriptPackScanListApi from '@/api/script/pack/scriptPackScanList'
import clusterSparingApi from '@/api/cluster/clusterSparing'
import scriptPublishVersionApi from '@/api/script/publish/scriptPublishVersion'

// crud交由presenter持有
const defaultCrud = CRUD({ title: '脚本打包任务', url: 'api/scriptPack/task/page', crudMethod: { ...scriptPackTaskApi }})
const defaultForm = {
  id: null,
  scriptPackName: null,
  clusterId: '',
  fileObtainingType: 'upload',
  gitUrl: null,
  gitBranchName: null,
  checkList: [],
  initScriptList: [],
  bizScriptList: [],
  cycleScriptList: [],
  schedulingConfig: [],
  checkListTmp: [],
  initScriptListTmp: [],
  bizScriptListTmp: [],
  cycleScriptListTmp: [],
  requirementCode: null,
  publishDate: null,
  scriptVersion: null,
  packState: 'SCANNING',
  publishTaskName: null,
  demandCode: '----',
  onlineDate: null,
  version: '----',
  createTime: null,
  createBy: null,
  lastUpdateBy: null,
  lastUpdateTime: null,
  del: null
}
export default {
  name: 'ScriptPack',
  components: { crudOperation, rrOperation, pagination, uploadScript, checkResult},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    return {
      packTaskId: null,
      nextStepLoading: false,
      isPackSubmitting: false,
      checkList: [],
      initScriptList: [],
      bizScriptList: [],
      cycleScriptList: [],
      checkListTmp: [],
      initScriptListTmp: [],
      bizScriptListTmp: [],
      cycleScriptListTmp: [],
      clusterLists: [],
      packStatusList: [
        { key: 'SCANNING', value: '扫描中' },
        { key: 'SCANFINISH', value: '扫描完成' }
      ],
      permission: {
        add: ['admin', 'scriptPack:add'],
        del: ['admin', 'scriptPack:del']
      },
      rules: {
        scriptPackName: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        clusterId: [
          { required: true, message: '请选择集群名称', trigger: 'blur' }
        ],
        gitUrl: [
          { required: true, message: '请输入git链接名称', trigger: 'blur' }
        ],
        gitBranchName: [
          { required: true, message: '请输入分支名称', trigger: 'blur' }
        ],
        requirementCode: [
          { required: true, message: '请输入需求编码', trigger: 'blur' }
        ],
        publishDate: [
          { required: true, message: '请输入选择发布日期', trigger: 'blur' }
        ],
        publishTaskName: [
          { required: true, message: '请输入发布包名称', trigger: 'blur' }
        ],
        onlineDate: [
          { required: true, message: '请选择上线日期', trigger: 'blur' }
        ],
        demandCode: [
          { required: true, message: '请输入发布编码', trigger: 'blur' }
        ]
      },
      active: 0
    }
  },
  created() {
    this.initData()
  },
  methods: {
    [CRUD.HOOK.beforeToAdd](crud) {
      this.active = 0
      this.form = crud.form
      this.checkListTmp = []
      this.initScriptListTmp = []
      this.bizScriptListTmp = []
      this.cycleScriptListTmp = []
      this.clusterLists = []
    },
    [CRUD.HOOK.beforeToEdit](crud) {
      this.active = 1
      this.packTaskId = crud.form.id
    },
    [CRUD.HOOK.beforeAddCancel](crud) {
      crud.refresh()
    },
    initData() {
      this.crud.resetQuery(true)
      this.clusterLists = []
      clusterSparingApi.findListByPage().then(res => {
        res.records.forEach((array) => {
          this.clusterLists.push({ key: array.id, value: array.clusterName })
        })
      })
    },
    getClusterName(clusterId) {
      return this.clusterLists.get(clusterId)
    },
    closeClick() {
      this.nextStepLoading = false
      this.crud.cancelCU()
      this.crud.resetForm()
    },
    async submitCU() {
      if (this.crud.form.id !== null) {
        this.active = 1
      } else {
        await this.$refs[ 'form' ].validate((valid) => {
          if (valid) {
            // 将下一步按钮置为运转中状态
            this.nextStepLoading = true
            this.formatInitScriptList(this.crud.form.initScriptList)
            scriptPackTaskApi.add(this.crud.form).then((res) => {
              // 点击关闭后修改状态，则后续全部修改
              if (this.nextStepLoading === true) {
                this.crud.form.id = res
                this.active = 1
                this.nextStepLoading = false
              }
            }).finally(() => {
              this.nextStepLoading = false
            })
          }
        })
      }
    },
    packScriptFile() {
      /*  this.crud.refresh()
      const id = this.crud.form.id
      scriptPackScanListApi.getListByTaskId(id).then(res => {
        if (res.length() === 0) {
          this.$notify({ title: '失败', message: '无扫描结果，请等待扫描结果或检查文件内容', type: 'error' })
        }
      })
      scriptPackScanListApi.findFailByTaskId(id).then(res => {
        if (res.length === 0) {
          this.active++
        } else {
          let fileNames = ''
          res.forEach(info => {
            fileNames = fileNames + info + ' '
          })
          this.crud.refresh()
          this.$notify({ title: '失败', message: '以下文件尚未扫描完成或存在尚未处理的检查异常' + fileNames, type: 'error' })
        }
      }) */
      this.closeClick()
    },
    submitPublishTask() {
      this.isPackSubmitting = true
      const data = {
        id: this.form.id,
        onlineDate: this.form.onlineDate,
        demandCode: this.form.demandCode,
        version: this.form.version
      }
      // 更新打包任务
      scriptPackTaskApi.edit(data)
      // 执行打包操作
      scriptPackTaskApi.pack(this.form).then(res => {
        this.crud.toQuery()
        this.crud.cancelCU()
        // 创建发布任务
        this.addScriptPublishTask(res)
      }).finally(() => {
        this.isPackSubmitting = false
      })
    },
    addScriptPublishTask(res) {
      const param = {
        scriptPublishName: res.publishTaskName,
        onlineDate: res.onlineDate,
        demandCode: res.demandCode,
        version: res.version,
        packageFileName: res.filePackName,
        packageFilePath: res.filePackPath,
        packTaskId: res.id,
        masterPackagePath: res.masterPackagePath,
        appointClusterId: res.clusterId
      }
      scriptPublishVersionApi.add(param)
    },
    formatCheckList(fileList) {
      if (fileList !== undefined && fileList != null && fileList.length > 0) {
        const newFileList = []
        fileList.forEach(item => {
          if (item.filePath !== undefined) {
            this.checkListTmp.push(item)
          }
        })
        this.checkListTmp.forEach(list => {
          if (list.filePath !== undefined) {
            newFileList.push(list.filePath)
          }
        })
        this.crud.form.checkList = newFileList
      }
    },
    formatInitScriptList(fileList) {
      if (fileList !== undefined && fileList != null && fileList.length > 0) {
        const newFileList = []
        let tempFilePath = ''
        fileList.forEach(item => {
          if (item.filePath !== undefined) {
            this.initScriptListTmp.push(item)
          }
        })
        this.initScriptListTmp.forEach(list => {
          if (list.filePath !== undefined) {
            newFileList.push(list.filePath)
            tempFilePath = list.filePath
          }
        })
        this.crud.form.initScriptList = newFileList
        this.crud.form.tempPackagePath = tempFilePath
      }
    },
    formatBizScriptList(fileList) {
      if (fileList !== undefined && fileList != null && fileList.length > 0) {
        const newFileList = []
        fileList.forEach(item => {
          if (item.filePath !== undefined) {
            this.bizScriptListTmp.push(item)
          }
        })
        this.bizScriptListTmp.forEach(list => {
          if (list.filePath !== undefined) {
            newFileList.push(list.filePath)
          }
        })
        this.crud.form.bizScriptList = newFileList
      }
    },
    formatCycleScriptList(fileList) {
      if (fileList !== undefined && fileList != null && fileList.length > 0) {
        const newFileList = []
        fileList.forEach(item => {
          if (item.filePath !== undefined) {
            this.cycleScriptListTmp.push(item)
          }
        })
        this.cycleScriptListTmp.forEach(list => {
          if (list.filePath !== undefined) {
            newFileList.push(list.filePath)
          }
        })
        this.crud.form.cycleScriptList = newFileList
      }
    },
    formatSchedulingConfig(fileList) {
      if (fileList !== undefined && fileList != null && fileList.length > 0) {
        const newFileList = []
        fileList.forEach(item => {
          newFileList.push(item.filePath)
        })
        this.crud.form.schedulingConfig = newFileList
      }
    }
  }
}
</script>
<style scoped>
.assist {
  min-height: 46px;
  color: #fff;
  background-color: #ff4949;
  border-color: #ff4949;
}
</style>
